package com.hz.foodstalls.interceptor;

import java.util.Map;

import com.hz.foodstalls.model.WxUser;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.ext.kit.JsonExtKit;
import com.jfinal.kit.HttpKit;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;

/**
 * 微信拦截器
 * 
 * @author zhj
 * @Createtime 20170808
 */
public class WxInterceptor implements Interceptor {

    @Override
    public void intercept(Invocation invocation) {
        Controller controller = invocation.getController();
        String code = controller.getRequest().getParameter("code");
        if (code != null && !"".equals(code)) {
            ApiConfig conf = ApiConfigKit.getApiConfig(controller.getRequest().getParameter("appId"));
            controller.getSession().setAttribute("appid", controller.getRequest().getParameter("appId"));
            String json = HttpKit.get("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + conf.getAppId()
                    + "&secret=" + conf.getAppSecret() + "&code=" + code + "&grant_type=authorization_code");
            Map<String, String> map = JsonExtKit.jsonToMap(json);
            String openid = map.get("openid");
            if (openid != null && !"".equals(openid)) {
                WxUser.dao.saveWxUser2(openid, controller.getRequest().getParameter("appId"), map.get("access_token"));
                controller.getSession().setAttribute("openid", openid);
            }
        }
        invocation.invoke();
    }
}
